<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog
            v-model="dialogVisible"
            title="选择调拨产品"
            width="1200px"
            :close-on-click-modal="false"
            :show-close="false"
        >
            <div class="select-product-dialog">
                <!-- 左侧仓库列表 -->
                <div class="group-list">
                    <div class="group-title margin-bottom-10">
                      <div class="margin-bottom-10">仓库</div>
                        <el-input v-model="warehouseSearch" placeholder="搜索仓库" size="small" suffix-icon="Search" />
                    </div>
                    <el-menu
                        :default-active="activeWarehouse"
                        class="group-menu"
                        active-text-color="#6860FF"
                        @select="handleWarehouseSelect"
                    >
                        <el-menu-item
                            v-for="warehouse in filteredWarehouses"
                            :key="warehouse.id"
                            :index="warehouse.id"
                        >{{ warehouse.name }}</el-menu-item>
                    </el-menu>
                </div>
                <!-- 中间产品表格 -->
                <div class="product-table">
                    <el-input
                        v-model="productSearch"
                        placeholder="请输入产品名称/编号"
                        size="small"
                        prefix-icon="Search"
                        style="margin-bottom: 10px; width: 200px;"
                    />
                    <el-table
                        ref="productTableRef"
                        :data="filteredProducts"
                        border
                        style="width: 100%;"
                        @selection-change="handleSelectionChange"
                        :row-key="getRowKey"
                     
                    >
                        <el-table-column
                            type="selection"
                            width="50"
                            :reserve-selection="true"
                            :selectable="isSelectable"
                        />
                        <el-table-column prop="name" label="产品名称" >
                            <template #default="{ row }">
                                <div>{{ row.product.name }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="code" label="产品编号" >
                            <template #default="{ row }">
                                <div>{{ row.product.no }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="specification" label="规格型号" >
                            <template #default="{ row }">
                                <div>{{ row.product.specification }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="stock_num" label="库存数量" />
                    </el-table>
                </div>
                <!-- 右侧已选 -->
                <div class="selected-list">
                    <div class="selected-header">
                        <span>已选 {{ totalSelectedCount }} 项</span>
                        <el-link type="primary" @click="clearAllSelected" v-if="totalSelectedCount > 0">清空全部</el-link>
                    </div>
                    
                    <!-- 按仓库分组显示已选产品 -->
                    <div v-for="(group, warehouseId) in groupedSelectedProducts" :key="warehouseId" class="warehouse-group">
                        <div class="warehouse-header" @click="toggleWarehouseCollapse(warehouseId)">
                            <div class="warehouse-title">
                                <el-icon :class="{'is-rotate': !collapsedWarehouses[warehouseId]}">
                                    <ArrowRight />
                                </el-icon>
                                <span>{{ getWarehouseName(group) }} ({{ group.length }})</span>
                            </div>
                            <!-- <el-link type="primary" @click.stop="clearWarehouseSelected(warehouseId)">清空</el-link> -->
                        </div>
                        
                        <div v-show="!collapsedWarehouses[warehouseId]" class="warehouse-products">
                            <el-table :data="group" border style="width: 100%;">
                                <el-table-column prop="name" label="产品名称" >
                                    <template #default="{ row }">
                                        <div>{{ row.product.name }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="no" label="产品编号" >
                                    <template #default="{ row }">
                                        <div>{{ row.product.no }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="specification" label="规格型号" >
                                    <template #default="{ row }">
                                        <div>{{ row.product.specification }}</div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="60">
                                    <template #default="{ row }">
                                        <el-link type="danger" @click="removeSelected(row)">移除</el-link>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    
                    <div v-if="totalSelectedCount === 0" class="empty-selected">
                        <el-empty description="暂无选中产品" />
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button color="#626aef" type="primary" @click="confirmSelect">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive, onMounted, nextTick } from "vue";
import { ElMessage } from 'element-plus';
import { ArrowRight } from '@element-plus/icons-vue';
import api from "@/api";

interface Warehouse {
    id: string;
    name: string;
    [key: string]: any;
}

interface Product {
    id: string;
    name: string;
    code: string;
    specification: string;
    stock_num: string | number;
    warehouse_id: string;
    [key: string]: any;
}

const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    warehouses: {
        type: Array as () => Warehouse[],
        default: () => []
    },
    modelValue: {
        type: Array as () => Product[],
        default: () => []
    },
    selecList: {
        type: Array as () => any[],
        default: () => []
    }
});

const emit = defineEmits(['update:dialogVisible', 'update:modelValue', 'confirm']);

// 仓库和产品搜索
const warehouseSearch = ref('');
const productSearch = ref('');
const activeWarehouse = ref();
const selectedProducts = ref<Product[]>([]);
const collapsedWarehouses = ref<Record<string, boolean>>({});
const productTableRef = ref();

// 监听对话框显示状态
const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => {
        emit('update:dialogVisible', val);
    }
});

// 当前仓库的产品列表
const warehouseProducts = ref<Product[]>([]);


const getRowKey = (row: Product) => {
    return row.id;
}

// 监听对话框打开
watch(() => dialogVisible.value, (val) => {
    if (val) {
      
   
        // 如果有仓库，默认选中第一个
        if (props.warehouses && props.warehouses.length > 0) {
           // 如果有已选产品，优先选择第一个已选产品的仓库
            if (selectedProducts.value.length > 0) {
                const firstWarehouseId = selectedProducts.value[0].warehouse_id;
                if (firstWarehouseId && props.warehouses.some(w => String(w.id) === String(firstWarehouseId))) {
               
                    activeWarehouse.value = firstWarehouseId;
                } else {
        
                    activeWarehouse.value = props.warehouses[0].id;
                }
            } else {
             
                activeWarehouse.value = props.warehouses[0].id;
            }
            loadWarehouseProducts(activeWarehouse.value);
        }
    }else{
     
    }
});

// 过滤仓库列表
const filteredWarehouses = computed(() => {
    const warehouses = props.warehouses || [];
    if (!warehouseSearch.value) return warehouses;
    return warehouses.filter((w: Warehouse) => w.name.includes(warehouseSearch.value));
});



// 过滤产品列表
const filteredProducts = computed(() => {
    // if (!productSearch.value) 
    return warehouseProducts.value;
    // return warehouseProducts.value.filter(
    //     (p) => p.name?.includes(productSearch.value) || p.code?.includes(productSearch.value)
    // );
});

// 按仓库分组的已选产品
const groupedSelectedProducts = computed(() => {
    const groups: Record<string, Product[]> = {};
    selectedProducts.value.forEach(product => {
        const warehouseId = product.warehouse_id || 'unknown';
        if (!groups[warehouseId]) {
            groups[warehouseId] = [];
        }
        groups[warehouseId].push(product);
    });
    return groups;
});

// 已选产品总数
const totalSelectedCount = computed(() => {
    return selectedProducts.value.length;
});

// 获取仓库名称
function getWarehouseName(warehouseArray: Product[]): string {
    const warehouse = filteredWarehouses.value.find(w => w.id == warehouseArray[0].warehouse_id);

    return warehouse ? warehouse.name : '未知仓库';
}

// 切换仓库折叠状态
function toggleWarehouseCollapse(warehouseId: string) {
    collapsedWarehouses.value[warehouseId] = !collapsedWarehouses.value[warehouseId];
}

// 设置表格选中状态
function setTableSelections() {
    if (!productTableRef.value) return;
    
    // 清除所有选择
    productTableRef.value.clearSelection();
    
    // 获取当前仓库的已选产品
    const currentWarehouseSelected =  props.selecList;
    
    console.log(currentWarehouseSelected,'currentWarehouseSelected');
    
    // console.log('当前仓库所有产品:', warehouseProducts.value);
    
    // 为每个已选产品设置选中状态
    nextTick(() => {
        warehouseProducts.value.forEach(product => {
            const isSelected = currentWarehouseSelected.some(
                p => String(p.id) == String(product.id) || 
                     (p.product_no && product.product && String(p.product_no) == String(product.product.no))
            );

            console.log(warehouseProducts.value,'isSelected');
            
            if (isSelected) {
                console.log(product,'productXxXs');
                productTableRef.value.toggleRowSelection(product, true);
            }
        });
    });
}

// 加载仓库产品
async function loadWarehouseProducts(warehouseId: string) {
    try {
        const res = await api.product.product_stock_list({ warehouse_id: warehouseId });
        if (res.code === 200) {
            warehouseProducts.value = res.data.data || [];
            // 标记产品所属仓库
            warehouseProducts.value.forEach(product => {
                product.warehouse_id = warehouseId;
            });
            
            // 设置表格选中状态
            nextTick(() => {
                // console.log('加载仓库产品后设置选中状态');
                setTableSelections();
            });
        }
    } catch (error) {

        warehouseProducts.value = [];
    }
}

// 选择仓库
function handleWarehouseSelect(warehouseId: string) {
    activeWarehouse.value = warehouseId;
    loadWarehouseProducts(warehouseId);
}

// 表格选择变化
function handleSelectionChange(selection: Product[]) {
  
    
    // 找出新选中的产品
    const newSelected = selection.filter(item => 
        !selectedProducts.value.some(p => 
            (p.id === item.id && p.warehouse_id === item.warehouse_id) || 
            (p.product && item.product && p.product.no === item.product.no && p.warehouse_id === item.warehouse_id)
        )
    );
 
    // 找出取消选中的产品（仅限当前仓库）
    const currentWarehouseProducts = selectedProducts.value.filter(
        p => p.warehouse_id === activeWarehouse.value
    );
 
    
    const deselected = currentWarehouseProducts.filter(
        item => !selection.some(s => 
            s.id === item.id || 
            (s.product && item.product && s.product.no === item.product.no)
        )
    );
 
    
    // 更新选中列表
    selectedProducts.value = [
        ...selectedProducts.value.filter(p => 
            p.warehouse_id !== activeWarehouse.value || 
            !deselected.some(d => 
                d.id === p.id || 
                (d.product && p.product && d.product.no === p.product.no)
            )
        ),
        ...newSelected
    ];

    
    
    // 初始化新选中仓库的折叠状态
    newSelected.forEach(product => {
        if (product.warehouse_id && !collapsedWarehouses.value.hasOwnProperty(product.warehouse_id)) {
            collapsedWarehouses.value[product.warehouse_id] = false; // 默认展开
        }
    });
}

// 判断产品是否可选
function isSelectable(row: Product): boolean {
    return true;
}

// 移除选中产品
function removeSelected(row: Product): void {
    selectedProducts.value = selectedProducts.value.filter(p => !(p.id === row.id && p.warehouse_id === row.warehouse_id));
    
    // 如果当前显示的是该产品所在仓库，更新表格选中状态
    if (row.warehouse_id === activeWarehouse.value && productTableRef.value) {
        const tableRow = warehouseProducts.value.find(p => p.id === row.id);
        if (tableRow) {
            productTableRef.value.toggleRowSelection(tableRow, false);
        }
    }
}


// 清空所有选中产品
function clearAllSelected() {
    selectedProducts.value = [];
    
    // 清空表格选中状态
    if (productTableRef.value) {
        productTableRef.value.clearSelection();
    }
}

// 关闭对话框
function closeDialog() {
    emit('update:dialogVisible', false);
}

// 确认选择
function confirmSelect() {
    if (selectedProducts.value.length === 0) {
        ElMessage.warning('请至少选择一个产品');
        return;
    }
    
    emit('update:modelValue', selectedProducts.value);
    emit('confirm', selectedProducts.value);
    emit('update:dialogVisible', false);
}
</script>

<style lang="scss" scoped>
::v-deep .el-menu-item {
    height: 38px;
}

::v-deep .el-menu-item.is-active {
    color: #6860FF;
    background-color: #6860ff29;
}

:deep(.el-dialog) {
    --el-dialog-padding-primary: 0px;
}

:deep(.el-dialog__header) {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

:deep(.dialog-footer) {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #000;
}

:deep(.el-dialog__body) {
    padding: 20px 10px;
    padding-right: 30px;
}

.select-product-dialog {
    display: flex;
    min-height: 400px;
    gap: 10px;
}

.group-list {
    width: 220px;
    border-right: 1px solid #eee;
    padding: 10px 10px 10px 10px;
    background: #fafbfc;
}

.group-title {
    font-weight: bold;
    margin-bottom: 10px;
}

.group-menu {
    border: none;
    background: transparent;
}

.product-table {
    flex: 1;
    padding: 10px 20px;
    border: 1px solid #eee;
    background: #fff;
}

.selected-list {
    width: 400px;
    padding: 10px 10px 10px 20px;
    border: 1px solid #eee;
    overflow-y: auto;
    max-height: 500px;
}

.selected-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    margin-bottom: 10px;
}

.warehouse-group {
    margin-bottom: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

.warehouse-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background-color: #f5f7fa;
    cursor: pointer;
    border-bottom: 1px solid #ebeef5;
}

.warehouse-title {
    display: flex;
    align-items: center;
    font-weight: bold;
}

.warehouse-products {
    padding: 10px;
}

.is-rotate {
    transform: rotate(90deg);
    transition: transform 0.3s;
}

.empty-selected {
    padding: 20px 0;
    text-align: center;
}
</style>
